store = require 'store2'
KEY_LOG = 'timer/log'
DAY = 86400000



module.exports = (path)->
    $.doc_title '倒计时'
    @find('.macS').html require("./init.slm")
    _interval = 0
    key = 'timer/minute'
    input = @find('input')
    input.val(store.get(key) or 15)
    timer = @find(".timer")

    table = =>
        log = store.get(KEY_LOG)
        _ = $.html()
        if log
            li = []
            for k,v of log
                li.push([k,v])
            li.sort(
                (a,b)=>
                    b[0]-a[0]
            )
            _ "<table>"

            _ """<tr><th>序号</th><th class=date>日期</th><th>次数</th></tr>"""
            len = li.length
            for [day, count], pos in li
                _ """<tr><td>#{len-pos}</td><td>#{$.isodate day}</td><td>#{count}</td></tr>"""
            _ "</table>"
        @find('.TXT').html _.html()
    table()
    TIMER = $(".TIMER")
    close = ->
        TIMER.hide()
        FORM.show()

    TIMER.find('.I-close').click close

    TIMER.find('.Itimer-reload').click ->
        FORM.submit()
        false

    ICON = TIMER.find '.ico'
    _timer_icon = 0
    icon_show = ->
        ICON.show()
        clearTimeout _timer_icon
    TIMER.click ->
        icon_show()
        _timer_icon = setTimeout(
            ->
                ICON.hide()
            10000
        )

    FORM = @find('form').submit ->
        me = $(@).hide()
        TIMER.show()
        val = (input.val().trim() - 0)  or 0
        store.set key, val
        seconds = parseInt((val)*60)
        clearInterval _interval
        begin = new Date()
        timer.text seconds
        ICON.hide()
        _interval = setInterval(
            =>
                remain = seconds - parseInt((new Date-begin)/1000)
                timer.text(
                    remain
                )
                if remain <= 0
                    clearInterval(_interval)
                    btn = $ '<button class="btn">+1</button>'
                    day = parseInt(begin/DAY)
                    btn.click =>
                        close()
                        log = store.get(KEY_LOG) or {}
                        log[day] = (log[day] or 0 )+1
                        store.set(KEY_LOG, log)
                        table()
                        false
                    timer.html(btn)
                    icon_show()
            1000
        )
        return false
    return
